import { Signal } from "./utils/signal";

// 最大每帧之间延迟
const maxDtMs = 1000;
// 重置延迟
const resetDtMs = 16;

export class AnimationFrame{
  constructor(){
    this.frameEmitted = new Signal();

    this.lastTime = performance.now();
  }

  start(){
    assert(window.requestAnimationFrame, 'requestAnimationFrame不支持');
    this.handleAnimationFrame();
  }

  handleAnimationFrame(time){
    let dt = time - this.lastTime;

    if(dt > maxDtMs){
      dt = resetDtMs
    }

    try{
      this.frameEmitted.dispatch(dt);
    } catch(err){
      console.error(err);
    }

    this.lastTime = time;
    window.requestAnimationFrame(this.handleAnimationFrame.bind(this));
  }
}